package com.guigu.ssyx.acl.helper;

import com.atguigu.ssyx.model.acl.Permission;

import java.util.ArrayList;
import java.util.List;

public class PermissionHelper {

    /**
     * 使用递归的方法建菜单
     * @param treeNodes
     * @return
     * */

    public static List<Permission> build(List<Permission> treeNodes){
        ArrayList<Permission> permissions = new ArrayList<>();
        for (Permission permission : treeNodes) {
            if(permission.getPid() ==0){
                permission.setLevel(1);
                permissions.add(findChildren(permission,treeNodes));
            }
        }
        return permissions;
    }

    public static Permission findChildren(Permission permission, List<Permission> treeNodes){
        permission.setChildren(new ArrayList<Permission>());

        for (Permission it : treeNodes) {
            if(permission.getId().longValue() == it.getPid().longValue()){
                int level = permission.getLevel() + 1;
                it.setLevel(level);
                if(permission.getChildren() == null){
                    permission.setChildren(new ArrayList<Permission>());
                }
                permission.getChildren().add(findChildren(it,treeNodes));
            }
        }
        return permission;
    }

}
